package com.cn.parks.servlet;

import com.cn.parks.dao.UserDao;
import com.cn.parks.dao.impl.UserDaoImpl;
import com.cn.parks.entity.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

/**
 * 用户登录Servlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserDao userDao = new UserDaoImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        System.out.println("LoginServlet - doPost start");  // 调试日志

        // 获取登录参数
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        System.out.println("Login attempt - userName: " + userName);  // 调试日志

        try {
            // 验证用户登录
            User user = userDao.login(userName, password);
            
            System.out.println("Login result - user: " + (user != null ? user.getUserName() : "null"));  // 调试日志
            
            if (user != null) {
                // 登录成功，将用户信息存入session
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                session.setAttribute("userId", user.getUserId());
                session.setAttribute("roleId", user.getRoleId());
                
                // 返回成功响应
                String jsonResponse = "{\"success\":true,\"message\":\"登录成功\"}";
                System.out.println("Sending response: " + jsonResponse);  // 调试日志
                response.getWriter().write(jsonResponse);
            } else {
                // 返回失败响应
                String jsonResponse = "{\"success\":false,\"message\":\"用户名或密码错误\"}";
                System.out.println("Sending response: " + jsonResponse);  // 调试日志
                response.getWriter().write(jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 返回错误响应
            String jsonResponse = "{\"success\":false,\"message\":\"系统错误：" + e.getMessage() + "\"}";
            System.out.println("Sending error response: " + jsonResponse);  // 调试日志
            response.getWriter().write(jsonResponse);
        }
    }
} 